Ext.onReady(function() {
			//00待审核 01审核通过 02审核不通过 10已生效 20失效
	 var statusStoreList = [
	                         {"value":"00","text":"待审核"},
	                         {"value":"01","text":"审核通过"},
	                         {"value":"02","text":"审核不通过"},
	                         {"value":"10","text":"已生效"},
	                         {"value":"20","text":"无效"}
	                         ];
	   var statusStore = Ext.data.Store({
	    	autoDestroy: true,
	        fields :["value","text"],
	        data : statusStoreList
	    });
	   
	   
	   
	   
	   var valuationStoreList = [
		                         {"value":"1","text":"建筑面积"},
		                         {"value":"2","text":"套内面积"},
		                         {"value":"3","text":"套(别墅/排屋)"},
		                         {"value":"4","text":"个(车位)"}
		                         ];
		   var valuationStore = Ext.data.Store({
		    	autoDestroy: true,
		        fields :["value","text"],
		        data : valuationStoreList
		    });
	
	
			//日期格式化
			Date.prototype.Format = function (fmt) { 
			    var o = {
			        "M+": this.getMonth() + 1, //月份 
			        "d+": this.getDate(), //日 
			        "h+": this.getHours(), //小时 
			        "m+": this.getMinutes(), //分 
			        "s+": this.getSeconds(), //秒 
			        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
			        "S": this.getMilliseconds() //毫秒 
			    };
			    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
			    for (var k in o)
			    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			    return fmt;
			}
			var clickListener = function(node, event) {
				var id = event.data.id;
				$("#tree_id").val(id);
				
				Ext.Ajax.request({
					url: jypath+'/marketing/priceScheme/findProjectLink',
					params:{
						treeId:id
					},
					callback: function (options, success, response) {
						 if (success) {
							 var result = JSON.parse(response.responseText);
							 if(result.res=="1"){
								 Ext.getCmp("secheme").setValue(result.obj);
							 }
			        	 }
					}
					
				});
				
				
				
				gridStore.load();
			}

			var form = Ext.create("Ext.form.Panel", {
				region : 'north',
				height : 150,
				title : "查询条件",
				collapsible : true, // 可折叠
				autoScroll : false, // 自动创建滚动条
				defaultType : 'textfield',
				defaults : {
					anchor : '80%'
				},
				fieldDefaults : {
					flex : 1,
					margin : 2,
					labelWidth: 80,
			        labelAlign: "right",
			        margin: "5 0 0 0"
				},

				items : [
					//权限资源隐藏字段
            		{xtype:"textfield", id: "resourcesCode", name:"resourcesCode", value: resourcesCode, hidden: true},
            		{xtype:"textfield", id: "resourcesName", name:"resourcesName", value: "resName_price_list", hidden: true},
					{
					xtype : "container",
					layout : "hbox",
					items : [ {
						xtype : 'combobox',
						fieldLabel : '状态',
						store:statusStore,
				    	displayField: "text",
				    	valueField:"value",
				    	id:'combox_status'
					}, {
						xtype : "textfield",
						fieldLabel : "价格方案",
						id:"input_name"
					}]
				}, {
					xtype : "container",
					layout : "hbox",
					items : [ {
						xtype : "datefield",
						name : "phone",
						fieldLabel : "方案执行时间",
						format : 'Y-m-d',
						id:'exTime'
					}, {
						xtype : "datefield",
						name : "phone",
						fieldLabel : "方案失效时间",
						format : 'Y-m-d',
						id:'inTime'
					} ]
				}, {
					xtype : "container",
					layout : "hbox",
					items : [ {
						xtype : 'combobox',
						fieldLabel : '计价方式',
						id:"valuationType_combox",
						store:valuationStore,
						displayField: "text",
				    	valueField:"value"
					}, {
						xtype : 'textfield',
						fieldLabel : '方案房产',
						id:'secheme'
					} ]

				}

				]

			});
			/**
			 * 左侧项目树
			 */
			var treeStoreJson = null;
			var treeParams = {};
			treeParams["resourcesCode"] = "menu_0003_0001";
			treeParams["resourcesName"] = "resName_pro_list";
			$.ajax({
				type : "POST",
				url : jypath + "/marketing/priceScheme/treeNodeList",
				dataType : "json",
				data: treeParams,
				async : false,
				success : function(data) {
					treeStoreJson = data;
				}
			});
			var store = Ext.create('Ext.data.TreeStore', {
				root : {
					expanded : true,
					children : treeStoreJson
				}
			});
			
			var treePanel = Ext.create('Ext.tree.Panel', {
				id : 'menuTree',
				region : 'west',
				split : true,
				title : '项目树',
				width : 220,
				stateId : 'appnav',
				stateful : true,
				margins : '2 0 0 0',
				collapsible : true,
				animCollapse : true,
				xtype : 'treepanel',
				rootVisible : false,
				store : store,
				listeners : {
					itemclick : clickListener
				}
			});

			var gridStore = Ext.create('Ext.data.Store', {
				fields : [ "id", "name", "secheme", "executionDate",
						"status", "valuationType", "createCN","invalidCN","taskUserName","invalidCheckName" ],
				pageSize : 10, // 页容量5条数据
				// 是否在服务端排序 （true的话，在客户端就不能排序）
				remoteSort : false,
				proxy : {
					type : 'ajax',
					url : jypath + '/marketing/priceScheme/list',
					reader : { // 这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
						type : 'json', // 返回数据类型为json格式
						root : 'rows', // 数据
						totalProperty : 'total' // 数据总条数
					}
				},
				autoLoad : true
			// 即时加载数据
			});

			var grid = Ext .create( 'Ext.grid.Panel', {
				region : 'center',
				store : gridStore,
				columnLines : true,
				columns : [{  
		            text : "查看",  
		          	dataIndex: 'id',
		          	width:'5%',
		            renderer : function(val) {
		                return "<a href='javascript:parent.openMenu(\"0\",\"sch_"+val+"\",\"\",\"价格方案详情\",\"/marketing/priceScheme/schemeView?id="+val+"&1=1\")' >查看</a>";
		            }
		        },{
					text : '方案名称',
					width:'15%',
					dataIndex : 'name'

				},{
					text : '方案房产',
					width:'20%',
					dataIndex : 'secheme'
				},{
					text : '方案执行日期',
					width:'10%',
					dataIndex : 'executionDate',
					renderer : function(val) {
						if(val!=null&&val!=""){
							return new Date(val).Format("yyyy-MM-dd");
						}
						return null;
					}
				},{
					text : '状态',
					width:'5%',
					dataIndex : 'status',
					renderer:function(val){
						////00待审核 01审核通过 02审核不通过 10已生效 20失效
						 if(val=="00"){
							 return "待审核";
						 }else if(val=="01"){
							 return "审核通过";
						 }else if(val=="02"){
							 return "审核不通过";
						 }else if(val=="10"){
							 return "已生效";
						 }else if(val=="20"){
							 return "无效";
						 }
					}
				},{
					text : '计价方式',
					width:'10%',
					dataIndex : 'valuationType',
					renderer:function(val){
						 if(val=="1"){
							 return "建筑面积";
						 }else if(val=="2"){
							 return "套内面积";
						 }else if(val=="3"){
							 return "套(别墅/排屋)";
						 }else if(val=="4"){
							 return "个(车位)";
						 }
					}
				},{
					text : '创建人',
					width:'7%',
					dataIndex : 'createCN'
				},{
					text : '方案审核人',
					width:'8%',
					dataIndex : 'taskUserName'
				},{
					text : '失效人',
					width:'10%',
					dataIndex : 'invalidCN'
				},{
					text : '失效审核人',
					width:'10%',
					dataIndex : 'invalidCheckName'
				}],
				selModel : {
					selType : 'rowmodel'
				},
				title : '方案列表',
				viewConfig : {
					stripeRows : true
				},
				dockedItems : [ {
					xtype : 'pagingtoolbar',
					store : gridStore, // GridPanel中使用的数据
					dock : 'bottom',
					displayInfo : true,
					emptyMsg : "没有数据",
					displayMsg : "显示从{0}条数据到{1}条数据，共{2}条数据"
				} ],
				tbar : [{
							hidden:priceSchemeAdd,
							text : '新增',
							icon : jypath
									+ '/resources/ExtJSicons/book_add.png',
							handler : showAlert
						}, "-",
						{
							hidden:priceSchemeList,
							text : '查询',
							icon : jypath
									+ '/resources/ExtJSicons/book_key.png',
							handler : queryGrid
						},{
							hidden:priceSchemeDelete,
							text : '删除',
							icon : jypath
									+ '/resources/ExtJSicons/book_delete.png',
							handler : deletePriceScheme
						},{
							hidden:priceSchemeInvalid,
							text : '失效',
							icon : jypath + '/resources/ExtJSicons/book_error.png',
							handler : editStatus,
							id: 'invalidBtn'
						},{
							hidden:priceSchemeView,
							text : '查看',
							icon : jypath + '/resources/ExtJSicons/book_open.png',
							handler : openInfo
				}],
				listeners:{
					'select': function(grid, record, rowIndex, e){
						if(record){
							if(record.data.status == 10 && !priceSchemeInvalid){
								Ext.getCmp("invalidBtn").show();
							}else{
								Ext.getCmp("invalidBtn").hide();
							}
						}
					}
				}
			});
		
			function showAlert() {
				var treeId = $("#tree_id").val();
				if (treeId == null || treeId == "") {
					Ext.MessageBox.alert("系统提示", "请选择项目树的某个节点,进行新增价格方案!");
				} else {
					var url="/marketing/priceScheme/addView?treeId=" + treeId+"&1=1";
					parent.openMenu("0",treeId,"","新增价格方案",url);
				}

			}
			var form1 = Ext.create('Ext.panel.Panel', {
				region : 'center',
				collapsible : true, // 可折叠
				autoScroll : false, // 自动创建滚动条
				items : [ form, grid ]
			});
			var viewport = Ext.create('Ext.Viewport', {
				layout : 'border',
				items : [ treePanel, form1 ]
			});

			function queryGrid(){
				gridStore.load();
			}
			
			function deletePriceScheme(){
				
				var record = grid.getSelectionModel().getLastSelected();
				if(record!=undefined){
					 Ext.MessageBox.confirm("提示","是否确定删除?",function(btn,txt){
						 if(btn=="yes"){
							 Ext.Ajax.request({
                    			 url: jypath+'/marketing/priceScheme/delete',
                                 params: { id: record.data.id},
                                 method: 'POST',
                                 callback: function (options, success, response) {
                                	 if (success) {
                                		 Ext.MessageBox.alert("系统提示","删除成功");
                                		 gridStore.reload();
                                	 }else{
                                		 Ext.MessageBox.alert("系统提示","删除失败");
                                	 }
                                 }
                    		});
						 }
					 });
				}else{
					Ext.MessageBox.alert("系统提示", "请选择一行进行删除!");
					
				}
				
			}
			
			function updateStatusMethad(parent){
				Ext.Ajax.request({
       			 url: jypath+'/marketing/priceScheme/edit',
                    params: parent,
                    method: 'POST',
                    callback: function (options, success, response) {
                   	 if (success) {
                   		 Ext.MessageBox.alert("系统提示","设置成功");
                   		 gridStore.reload();
                   	 }else{
                   		 Ext.MessageBox.alert("系统提示","设置失败");
                   	 }
                    }
       		});
			}
			
		function openInfo(){
			var record = grid.getSelectionModel().getLastSelected();
			if(record!=undefined){
				var url = "/marketing/priceScheme/schemeView?id="+record.data.id+"&1=1";
				var tabKey = "sch_"+record.data.id;
				parent.openMenu("0",tabKey,"","价格方案详情",url);
			}else{
				Ext.MessageBox.alert("系统提示", "请选择一行进行查看!");
			}
		}
			
			function editStatus(){
				var record = grid.getSelectionModel().getLastSelected();
				console.log(record);
				if(record){
					if(record.data.status != "10"){
						Ext.MessageBox.alert("系统提示", "已生效价格方案才能做无效操作!!!");
						return;
					}
/*					var parent= {
							id:record.data.id,
							status:20,
							type:1
					}
					updateStatusMethad(parent);*/
					location.href=jypath+"/marketing/priceScheme/toInvalid?priceSchemeId="+record.data.id;
				}else{
					Ext.MessageBox.alert("系统提示", "请选择一行进行设置!");
				}
			}
			
			gridStore.on("beforeload",function(){
				var str = $("#tree_id").val();
		        Ext.apply(gridStore.proxy.extraParams, {
		        	status:Ext.getCmp('combox_status').getValue(),
		        	name:Ext.getCmp('input_name').getValue(),
		        	valuationType:Ext.getCmp('valuationType_combox').getValue(),
		        	exTime:dateFormat(Ext.getCmp('exTime').getValue()),
		        	inTime:dateFormat(Ext.getCmp('inTime').getValue()),
		        	//secheme:Ext.getCmp('secheme').getValue(),
		        	treeId:str,
		        	resourcesName: Ext.getCmp('resourcesName').getValue()
	        	});
				
		        Ext.apply(gridStore.proxy.extraParams, {
		        	status:Ext.getCmp('combox_status').getValue(),
		        	name:Ext.getCmp('input_name').getValue(),
		        	valuationType:Ext.getCmp('valuationType_combox').getValue(),
		        	exTime:dateFormat(Ext.getCmp('exTime').getValue()),
		        	inTime:dateFormat(Ext.getCmp('inTime').getValue()),
		        	//secheme:Ext.getCmp('secheme').getValue(),
		        	treeId:str,
		        	resourcesName: Ext.getCmp('resourcesName').getValue()
	        	});
		        var newResCode = resourcesCode + ",menu_0003_0001";
		        gridStore.proxy.extraParams.resourcesCode = newResCode;
			});

		
			
			function dateFormat(value){ 
			    if(null != value){ 
			        return Ext.Date.format(new Date(value),'Y-m-d H:i:s'); 
			    }else{ 
			        return null; 
			    } 
			} 
		});